<template>
  <view>
    <Navbar :title="userData.mall ? (userData.mall.shop_name || '青创云店') : '青创云店'"></Navbar>
    <view class="u-flex-col u-back-white" style="height: calc(100vh - 160px)">
      <view class="u-p-20 u-p-t-30 u-back-gold">
        <u-search shape="round" v-model="keyword" bg-color="#fff" :show-action="false" height="80" placeholder="搜索商品信息"
          @search="onSearchGoods()" @clear="onSearchGoods()"></u-search>
      </view>
      <view class="shop_content" style="min-height: 0;"><!-- :style="{height: goodsHeight + 'px'}" -->
        <!-- <view class="shop_left">
					<view :class="menuItem.check ? 'check' : 'common'" v-for="menuItem in menuList" :key="menuItem.id"
						@click="onChooseMenu(menuItem)">
						{{menuItem.name}}
					</view>
				</view> -->
        <view class="shop_right">
          <view class="overlay" @click="onCloseDrawer()" v-if="drawerStatus"></view>
          <view>
            <view class="shrink" v-if="!drawerStatus">
              <view class="category">
                <view :class="catrgoryItem.check ? 'check' : 'common'" v-for="catrgoryItem in categoryList"
                  :key="catrgoryItem.id" @click="onChooseCategory(catrgoryItem)">{{ catrgoryItem.name }}
                </view>
              </view>
              <view class="arrow" @click="onOpenDrawer()">
                <u-icon name="arrow-down"></u-icon>
              </view>
            </view>
            <view class="expand" v-else>
              <view class="u-flex u-row-between">
                <view>全部分类</view>
                <u-icon name="arrow-up" @click="onCloseDrawer()"></u-icon>
              </view>
              <view class="category">
                <view :class="catrgoryItem.check ? 'check' : 'common'" v-for="catrgoryItem in categoryList"
                  :key="catrgoryItem.id" @click="onChooseCategory(catrgoryItem)">{{ catrgoryItem.name }}
                </view>
              </view>
            </view>
          </view>
          <view style="overflow-y: auto;">
            <scroll-view scroll-y="true" class="u-height-100" @scrolltolower="onLoadGoodsData">
              <view class="goods_item" v-for="goodsItem in goodsList" :key="goodsItem.id"
                @click="onSwitchDetail(goodsItem.id)">
                <image :src="goodsItem.head_image[0]"></image>
                <view class="u-flex-1 u-m-l-20 u-flex-col u-row-between" style="height: 150rpx;min-width: 0;">
                  <view>
                    <view class="u-font-30 u-font-bold">{{ goodsItem.name }}</view>
                    <view class="u-font-24 u-color-gray u-m-t-5 u-ellipsis">{{ goodsItem.des }}</view>
                  </view>
                  <view class="u-flex u-row-between">
                    <view>
                      <span class="u-font-bold u-font-24 u-color-red">¥</span>
                      <span class="u-font-bold u-font-32 u-color-red">{{ goodsItem.vip_price }}</span>
                      <span class="u-m-l-10 u-font-22 u-color-gray u-font-line">¥{{ goodsItem.price }}</span>
                    </view>
                    <view class="u-relative" @click.native.stop="onAddCart(goodsItem)">
                      <u-icon name="plus-circle-fill" color="#B3723E" size="52"
                        :class="drawerStatus ? 'drawerIcon' : ''"></u-icon>
                      <view class="num" v-if="goodsItem.num > 0">{{ goodsItem.num }}</view>
                    </view>
                  </view>
                </view>
              </view>
              <view>
                <Loadmore :status="pageData.status"></Loadmore>
              </view>
            </scroll-view>
          </view>
        </view>
      </view>
    </view>
    <view class="shop_bottom">
      <view class="shop_box">
        <view class="car" @click="cartPopupData.show = true">
          <u-icon name="shopping-cart" color="#fff" size="68"></u-icon>
          <view class="num" v-if="cartPopupData.num > 0">{{ cartPopupData.num }}</view>
        </view>
        <view class="u-flex">
          <view class="price">
            <span>¥</span>
            <span class="num">{{ cartPopupData.price }}</span>
          </view>
          <view class="button" @click="onSwitchPay()">去结算</view>
        </view>
      </view>
    </view>

    <!-- 购物车弹出窗 -->
    <u-popup mode="bottom" border-radius="20" height="800" v-model="cartPopupData.show">
      <view class="cart">
        <view class="u-flex u-row-between u-color-puce u-m-b-20">
          <view class="u-font-34 u-font-bold">购物车</view>
          <view class="u-flex" @click="onClearCart()">
            <u-icon name="shanchu" custom-prefix="custom-icon" size="40" color="#B67642"></u-icon>
            <view class="u-m-l-15">清空</view>
          </view>
        </view>
        <view class="goods">
          <scroll-view scroll-y="true" class="u-height-100">
            <view class="goods_item" v-for="cartItem in cartPopupData.list" :key="cartItem.id">
              <image :src="cartItem.goods.head_image[0]"></image>
              <view class="u-flex-1 u-m-l-20 u-flex-col u-row-between" style="height: 150rpx">
                <view>
                  <view class="u-font-30 u-font-bold">{{ cartItem.goods.name }}</view>
                  <view class="u-font-24 u-color-gray u-m-t-5 u-ellipsis">{{ cartItem.goods.des }}</view>
                </view>
                <view class="u-flex u-row-between">
                  <view>
                    <span class="u-font-bold u-font-24 u-color-red">¥</span>
                    <span class="u-font-bold u-font-32 u-color-red">{{ cartItem.goods.vip_price }}</span>
                    <span class="u-m-l-10 u-font-22 u-color-gray u-font-line">¥{{ cartItem.goods.price }}</span>
                  </view>
                  <view class="u-relative">
                    <u-number-box v-model="cartItem.num" @minus="onReductCart(cartItem.goods)"
                      @plus="onAddCart(cartItem.goods)"></u-number-box>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
        <view class="button" @click="onSwitchPay()">去结算</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import Navbar from '@/components/Navbar.vue'
import Loadmore from '@/components/Loadmore.vue'
import share from '@/mixins/share.js'
import {
  setUserStorageSync,
} from '@/utils/index.js'
import {
  userLogin,
  userInfo,
} from '@/network/api.js'
import { teaGoodsTypeList, teaGoodsList, teaCartList, teaCartAdd, teaCartReduce, teaCartClear } from '@/network/tea.js'
export default {
  mixins: [share],
  components: {
    Navbar,
    Loadmore
  },
  data() {
    return {
      userId: '',
      inviterId: '',
      userData: {},
      keyword: '',
      goodsHeight: 0,
      drawerStatus: false,
      menuList: [],
      menuCheckObj: {},
      categoryList: [],
      categoryCheckObj: {},
      goodsList: [],
      cartPopupData: {
        show: false,
        price: 0,
        num: 0,
        list: []
      },
      pageData: {
        page: 1,
        count: 0,
        status: 'loadmore'
      }
    }
  },
  async onLoad(options) {
    wx.hideShareMenu()
    //当用户未登录时，先进行登录
    await this.handleLogin()

    console.log(options, 'options');
    this.userId = uni.getStorageSync("user_id") ? uni.getStorageSync("user_id") : ''
    this.onGetGoodsHeight()
    this.onGetFirst()
    this.onGetUserCartList()
    this.inviterId = options.inviterId ? options.inviterId : ''
    this.mixinsShare.page = `/teaBureau/teaPointShop/teaPointShop?inviterId=${this.userId}`
    setTimeout(() => {
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      })
    }, 1000)
    this.handleGetUserInfo(options.inviterId)
  },
  methods: {
    handleLogin() {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success(res) {
            userLogin({
              code: res.code
            }).then(res => {
              setUserStorageSync(res.data)
              resolve(res.data)
            })
          }
        })
      })
    },
    handleGetUserInfo(inviterId) {
      userInfo({
        user_id: this.userId,
        is_share: inviterId ? 1 : ''
      }).then(res => {
        this.userData = res.data
      })
    },

    onGetGoodsHeight() {
      const _this = this
      uni.getSystemInfo({
        success: (res) => {
          const statusBarHeight = res.statusBarHeight || 0;
          const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
          const navBarHeight = menuButtonInfo.height + (menuButtonInfo.top - statusBarHeight) *
            2;
          uni.createSelectorQuery().in(this).select(".shop_bottom").boundingClientRect(data => {
            _this.goodsHeight = data.bottom - statusBarHeight - navBarHeight - 65 -
              data.height
          }).exec()
        },
        fail: (err) => { }
      })
    },
    async onGetUserCartList() {
      const res = await teaCartList({ user_id: this.userId, position: 2 })
      this.cartPopupData.list = res.data
      /* 同步数量 */
      this.cartPopupData.list.map(cartItem => {
        this.goodsList.map(goodsItem => {
          if (cartItem.goods_id == goodsItem.id) {
            goodsItem.num = cartItem.num
          }
        })
      })
      if (res.data.length == 0) {
        this.goodsList.map(item => item.num = 0)
      }
      /* 计算总价和数量 */
      let price = 0
      let num = 0
      res.data.map(item => {
        price += item.num * Number(item.goods.vip_price)
        num += item.num
      })
      this.cartPopupData.price = price
      this.cartPopupData.num = num
    },
    async onGetFirst() {
      const res = await teaGoodsTypeList()
      res.data.map((item, index) => {
        if (index == 0) {
          item.check = true
          this.menuCheckObj = item
        } else {
          item.check = false
        }
      })
      this.menuList = res.data
      this.onGetSecond()
    },
    async onGetSecond() {
      const res = await teaGoodsTypeList({ type_id: this.menuCheckObj.id })
      res.data.map(item => {
        if (item.name == '全部') {
          item.check = true
          this.categoryCheckObj = item
        } else {
          item.check = false
        }
      })
      this.categoryList = res.data
      this.onReserveList()
      this.onGetGoodsList()
    },
    async onGetGoodsList() {
      const params = {
        keyword: this.keyword,
        page: this.pageData.page,
        limit: 10,
        // type_id: this.menuCheckObj.id,
        type_id: this.categoryCheckObj.id,
        position: 2
        // type_level_id: this.categoryCheckObj.id
      }
      const res = await teaGoodsList(params)
      this.pageData.count = res.data.count
      res.data.list.map(item => {
        this.goodsList.push(item)
      })
      if (this.goodsList.length == this.pageData.count) {
        this.pageData.status = 'nomore'
      } else {
        this.pageData.status = 'loadmore'
      }
      this.onGetUserCartList()
    },
    onSearchGoods() {
      this.onReserveList()
      this.onGetGoodsList()
    },
    onChooseMenu(val) {
      this.menuList.map(item => item.check = false)
      val.check = true
      this.menuCheckObj = val
      this.onGetSecond()
    },
    onChooseCategory(val) {
      this.categoryList.map(item => item.check = false)
      val.check = true
      this.drawerStatus = false
      this.categoryCheckObj = val
      this.onReserveList()
      this.onGetGoodsList()
    },
    onOpenDrawer() {
      this.drawerStatus = true
    },
    onCloseDrawer() {
      this.drawerStatus = false
    },
    /* 添加购物车 */
    async onAddCart(val) {
      const params = {
        user_id: this.userId,
        goods_id: val.id,
        num: 1,
        sku_id: '',
        position: 2
      }
      const res = await teaCartAdd(params)
      this.onGetUserCartList()
    },
    /* 减少购物车 */
    async onReductCart(val) {
      const params = {
        user_id: this.userId,
        goods_id: val.id,
        num: 1,
        sku_id: '',
        position: 2
      }
      const res = await teaCartReduce(params)
      this.onGetUserCartList()
    },
    /* 清空购物车 */
    async onClearCart() {
      const res = await teaCartClear({ user_id: this.userId, position: 2 })
      this.onGetUserCartList()
      this.cartPopupData.show = false
    },
    /* 跳转商品详情 */
    onSwitchDetail(id) {
      uni.navigateTo({
        url: `/teaBureau/teaGoodsDetail/teaGoodsDetail?id=${id}&inviterId=${this.inviterId}`
      })
    },
    /* 跳转订单确认 */
    onSwitchPay() {
      const userStauts = uni.getStorageSync("user_status")
      if (userStauts == 0) {
        uni.navigateTo({
					url: "/pages/register/registerShop"
				})
      }else{
        uni.navigateTo({
          url: "/teaBureau/teaPointOrder/teaPointOrder"
        })
      }
    },
    /* 重置商品列表 */
    onReserveList() {
      this.pageData.page = 1
      this.pageData.count = 0
      this.pageData.status = 'loadmore'
      this.goodsList = []
    },
    onLoadGoodsData() {
      if (this.pageData.status == 'nomore') {
        return
      } else {
        this.pageData.page++
        this.onGetGoodsList()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.shop_content {
  display: flex;
  justify-content: space-between;
  flex: 1;

  .shop_left {
    width: 20%;
    color: #808080;
    overflow-y: auto;

    .common {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 24rpx 0;
    }

    .check {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: 24rpx 0;
      background: #fff;
      position: relative;
    }

    .check::before {
      content: "";
      position: absolute;
      top: 20%;
      bottom: 0;
      left: 0;
      width: 12rpx;
      background-color: #E6BF91;
      transform: translateX(-50%);
      height: 60%;
    }
  }

  .shop_right {
    width: 100%;
    background: #fff;
    display: flex;
    flex-direction: column;
    position: relative;

    .overlay {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.2);
    }

    .shrink {
      display: flex;
      justify-content: space-between;

      .category {
        flex: 1;
        display: flex;
        padding: 20rpx;
        overflow-x: auto;

        .common {
          background: #F3F5F6;
          padding: 10rpx 20rpx;
          border-radius: 50rpx;
          margin-right: 15rpx;
          white-space: nowrap;
          font-size: 24rpx;
        }

        .check {
          background: #E6BF91;
          padding: 10rpx 20rpx;
          border-radius: 50rpx;
          margin-right: 15rpx;
          white-space: nowrap;
          font-size: 24rpx;
          color: #B3723E;
        }
      }

      .arrow {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 0 20rpx;
      }
    }

    .expand {
      width: 100%;
      background: #fff;
      padding: 20rpx;
      position: absolute;
      z-index: 9999;
      border-bottom-left-radius: 20rpx;
      border-bottom-right-radius: 20rpx;

      .category {
        display: flex;
        flex-wrap: wrap;
        padding: 30rpx 0 0 0;

        .common {
          background: #F3F5F6;
          padding: 18rpx 0;
          border-radius: 50rpx;
          margin-right: 15rpx;
          white-space: nowrap;
          font-size: 24rpx;
          width: 30%;
          text-align: center;
          margin-bottom: 20rpx;
        }

        .check {
          background: #E6BF91;
          padding: 18rpx 0;
          border-radius: 50rpx;
          margin-right: 15rpx;
          white-space: nowrap;
          font-size: 24rpx;
          color: #B3723E;
          width: 30%;
          text-align: center;
          margin-bottom: 20rpx;
        }
      }
    }

    .goods_item {
      display: flex;
      justify-content: space-between;
      padding: 20rpx;

      .num {
        position: absolute;
        right: -6rpx;
        top: -10rpx;
        background: #ee2424;
        color: #fff;
        padding: 4rpx 8rpx;
        font-size: 16rpx;
        border-radius: 50rpx;
        border: 1rpx solid #fff;
      }

      .drawerIcon {
        opacity: 0.4;
      }

      image {
        width: 150rpx;
        height: 150rpx;
        border-radius: 10rpx;
      }
    }
  }
}


.shop_bottom {
  position: fixed;
  z-index: 999;
  background: #fff;
  padding: 24rpx 24rpx 48rpx 24rpx;
  width: 100%;
  bottom: 0;
  box-shadow: 0px 0px 10rpx 0px rgba(0, 0, 0, 0.2);
  height: 150rpx;

  .shop_box {
    position: relative;
    display: flex;
    justify-content: flex-end;

    .car {
      position: absolute;
      top: -40rpx;
      left: 0;
      background: #B3723E;
      display: flex;
      padding: 20rpx;
      border-radius: 50rpx;

      .num {
        position: absolute;
        right: -8rpx;
        top: -10rpx;
        background: #fff;
        border: 1rpx solid #B3723E;
        padding: 2rpx 10rpx;
        border-radius: 50rpx;
        font-size: 24rpx;
        color: #B3723E;
        font-weight: bold;
      }
    }

    .price {
      color: #B3723E;
      font-weight: bold;

      .num {
        font-size: 44rpx;
        margin-left: 5rpx;
      }
    }

    .button {
      background: #B3723E;
      color: #fff;
      padding: 20rpx 60rpx;
      font-size: 30rpx;
      margin-left: 20rpx;
      border-radius: 50rpx;
    }
  }
}

.cart {
  padding: 30rpx 30rpx 50rpx 30rpx;
  display: flex;
  flex-direction: column;
  height: 100%;

  .goods_item {
    display: flex;
    justify-content: space-between;
    padding: 20rpx 0;

    .num {
      position: absolute;
      right: -6rpx;
      top: -10rpx;
      background: #ee2424;
      color: #fff;
      padding: 4rpx 8rpx;
      font-size: 16rpx;
      border-radius: 50rpx;
      border: 1rpx solid #fff;
    }

    .drawerIcon {
      opacity: 0.4;
    }

    image {
      width: 150rpx;
      height: 150rpx;
      border-radius: 10rpx;
    }
  }

  .goods {
    flex: 1;
    overflow-y: auto;
  }

  .button {
    background: #B3723E;
    color: #fff;
    padding: 20rpx 0;
    font-size: 30rpx;
    text-align: center;
    border-radius: 50rpx;
    margin-top: 30rpx;
  }
}
</style>